import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:gd_assistant/model/packageModel.dart';
import 'package:gd_assistant/model/userModel.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/page/user/healthRecordPage.dart';
import 'package:gd_assistant/page/user/selectPatientPage.dart';
import 'package:gd_assistant/page/user/userAppointment.dart';
import 'package:gd_assistant/util/RelativeDateFormat.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'dart:math' as math;

class detialUserPage extends StatefulWidget {
  detialUserPage({Key key, this.user}):super(key : key);
  Items user = Items();
  @override
  _detialUserPageState createState() => _detialUserPageState();
}

class _detialUserPageState extends State<detialUserPage> {
  bool isDark = false;
  List<PackageModel> _items;
  Widget contentCell(BuildContext context, PackageModel pack) {
    String orderStatus = "";
    if (pack.order.isExpire) {
      orderStatus = "(已过期)";
    }else if (pack.order.orderStatus == 900) {
      orderStatus = "(已退单)";
    }else if (pack.order.orderStatus == 1000) {
      orderStatus = "(已结单)";
    }
    return Container(
      color: isDark ? Colours.dark_bg_gray : Colors.white,
      child: Stack(
        children: <Widget>[
           Column(
            children: <Widget>[
              Container(
                margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
                child: Row(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.fromLTRB(0, 0, 20, 0),
                      child: ClipRRect(
                        child: ExtendedImage.network(
                          GlobalConfig.qiNiuUri + pack.order.icon,
                          height: 52,
                          width: 52,
                        ),
                      )
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(pack.order.name, style: TextStyle(fontSize: 16)),
                        Container(
                          width: MediaQuery.of(context).size.width - 112,
                          margin: EdgeInsets.only(top: 6),
                          child: Text("${pack.doctor.name} | ${pack.doctor.hospital}", 
                            style: TextStyle(color: Colors.grey),maxLines: 1,overflow: TextOverflow.ellipsis),
                        )
                      ],
                    )
                  ],
                ),
              ),
              Offstage(
                offstage: !pack.order.isPatientInfo,
                child: Container(
                  margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
                  width: MediaQuery.of(context).size.width,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text("就诊人: ${pack.order.patientName} | ${pack.order.patientSex} | ${pack.order.patientAge}", style: TextStyle(fontSize: 16)),
                      Container(
                        margin: EdgeInsets.only(top: 6),
                        child: Text("有效期至: ${RelativeDateFormat.YMDformat(pack.order.endAt)} ${orderStatus}", style: TextStyle(color: Colors.grey)),
                      )
                    ],
                  ),
                ),
              ),
              Offstage(
                offstage: !pack.order.isPatientInfo,
                child: Container(
                  margin: EdgeInsets.fromLTRB(0, 20, 20, 12),
                  width: MediaQuery.of(context).size.width,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      OutlineButton(
                        shape: StadiumBorder(),
                        onPressed: (){
                          Navigator.of(context).push(
                            CustomRoute(healthRecordPage(userid: widget.user.sId, orderid: pack.order.orderId, userName: pack.order.patientName, isExpire: pack.order.isExpire))
                          );  
                        },
                        child: Text("健康档案(${pack.order.dieaseCaseCount})"),
                        textColor: Colors.blue,
                        borderSide: BorderSide(color: Colors.blue),
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 20),
                      ),
                      OutlineButton(
                        shape: StadiumBorder(),
                        onPressed: (){
                          Navigator.of(context).push(
                            CustomRoute(userAppointentPage(userid: widget.user.sId, orderid: pack.order.orderId, userName: pack.order.patientName, age: pack.order.patientAge, sex: pack.order.patientSex, isExpire: pack.order.isExpire))
                          );   
                        },
                        child: Text("预约(${pack.order.appointmentCount}/${pack.order.appointmentTotalCount})"),
                        textColor: Colors.blue,
                        borderSide: BorderSide(color: Colors.blue),
                      )
                    ],
                  ),
                ),
              ),
              Offstage(
                offstage: pack.order.isPatientInfo,
                child: Container(
                  alignment: Alignment.centerRight,
                  margin: EdgeInsets.fromLTRB(10, 20, 10, 8),
                  child: ZLButton(
                    width: 130,
                    height: 35,
                    fontSize: 14,
                    title: "完善就诊人信息",
                    onTap: (){
                       Navigator.of(context).push(
                        CustomRoute(selectPatientPage(pack, widget.user.sId, callBack: (){
                          loadData();
                        }))); 
                    },
                  )
                ),
              ),
              
              Container(margin: EdgeInsets.only(left: 20),height: 0.3, color: Colors.grey[400])
            ],
          ),
           Positioned(
            right: 0,
            top: 18,
            child: Offstage(
              offstage: pack.order.pregnantWeekStr.length == 0,
              child: Container(
                padding: EdgeInsets.only(left:8, right:8, top: 3, bottom: 3),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(topLeft: Radius.circular(10), bottomLeft: Radius.circular(10)),
                    color: Colors.red[200]
                ),
                child: Text(pack.order.pregnantWeekStr,style: TextStyle(color: Colors.white, fontSize: 12)),
              ),
            )
          )
        ],
      )
    );
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }
   
  loadData() async {
    _items = await apiHandler.getMemberServicePackageList(widget.user.sId);
    //筛选未完成的订单
    // _items.removeWhere((v){
    //   return v.order.isPatientInfo == false;  
    // });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Scaffold(
      backgroundColor: isDark ? Colours.dark_bg_gray : Colors.white,
      body: MediaQuery.removePadding(
        context: context,
        child: CustomScrollView(
        slivers: <Widget>[
              SliverPersistentHeader(
                delegate: _SliverAppBarDelegate(
                  minHeight:MediaQuery.of(context).padding.top + 56,
                  maxHeight:260,
                  avatar: widget.user.avatar,
                  phone: widget.user.phoneNum != null ? widget.user.phoneNum : "",
                  name: widget.user.name,
                  isMember: widget.user.isMember
                ),
                pinned: true,
                floating: false,
              ),
              getDetialContent()
            ],
          ),
        )
      );
  }

  Widget getDetialContent(){
    num height = MediaQuery.of(context).size.height;
    if (_items != null && _items.length == 0) {
      return SliverList(
        delegate: new SliverChildBuilderDelegate(
          (BuildContext cext, int index){
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children:[
                Padding(padding: EdgeInsets.only(top:(height)/2-300)),
                Image.asset("images/dataBg.png",width: 180),
                Text("暂无服务")
              ]
            );
          },
          childCount: 1,
        ),
      );
    }
    return SliverList(
        delegate: new SliverChildBuilderDelegate(
          (BuildContext cext, int index){
            return contentCell(context, _items[index]);
          },
          childCount: _items != null ? _items.length : 0,
        ),
      );
  }
}



class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    this.avatar,
    this.name,
    this.phone,
    this.isMember
  });
    final double minHeight;
    final double maxHeight;
    String avatar;
    String name;
    String phone;
    bool isMember;
    bool isDark = false;
    @override
    double get minExtent => minHeight;
    @override
    double get maxExtent => math.max(maxHeight, minHeight);
    @override
    Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
      isDark = ThemeUtils.isDark(context);
      //根据shrinkOffset可变值 和maxHeight最大值  计算出50到100之间的曲线
      double imgSize = ((maxHeight-shrinkOffset)/maxHeight)*76 > 45 ? ((maxHeight-shrinkOffset)/maxHeight)*76 : 0;
      double opacity = (maxHeight-shrinkOffset)/maxHeight < 0.6 ? 0 : (maxHeight-shrinkOffset)/maxHeight;
      double topY = shrinkOffset > (173 - MediaQuery.of(context).padding.top) ? (173 - MediaQuery.of(context).padding.top) : shrinkOffset;
      Widget child = Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(isDark ? "images/dark_bg.jpg" : "images/mybg.png"),
            fit: BoxFit.cover
          )
        ),
        alignment: Alignment.center,
        child: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Opacity(
                opacity: opacity,
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.white, width: imgSize == 0 ? 0 : 2),
                    borderRadius: BorderRadius.circular((imgSize+2)/2.0),
                  ),
                  child: Stack(
                      children: <Widget>[
                        ClipRRect(
                          borderRadius: BorderRadius.circular(imgSize/2.0),
                          child: ExtendedImage.network(
                            GlobalConfig.qiNiuUri + ((avatar == null || avatar.isEmpty) ? "head.png" : avatar),
                            height: imgSize,
                            width: imgSize,
                          ),
                        ),
                        Positioned(
                          bottom: 0,
                          right: 0,
                          child: Offstage(
                            offstage: isMember == null || !isMember,
                            child: Image.asset("images/vip.png",width: 20,height: 20),
                          )
                        )
                      ],
                    )
                ),
              )
            ),
            Positioned(
              top: 185-topY,
              child: Container(
                width: MediaQuery.of(context).size.width,
                child: Text(name,
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: Colors.white),
                ),
              )
            ),
            Positioned(
              top: 215-topY,
              child: Opacity(
                opacity: opacity,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  child: Text(phone, 
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Colors.white))
                ),
              )
            ),
            Positioned(
                left: 0,
                top: MediaQuery.of(context).padding.top,
                child: IconButton(
                  icon: Icon(Icons.arrow_back_ios,color: Colors.white,),
                  onPressed: (){
                    Navigator.pop(context);
                  },
                )
            ),
          ],
        ),
      );
        return new SizedBox.expand(child: child);
  }
  @override
bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
  return maxHeight != oldDelegate.maxHeight ||
      minHeight != oldDelegate.minHeight;
  }
}
